import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'

Vue.use(VueRouter)

//导入子组件
import login from '../components/login/login'
import layout from '../components/layout'
import goodslist from '../components/goods/goodslist'
import goodsadd from '../components/goods/goodsadd'
import goodsedit from '../components/goods/goodsedit'
import category from '../components/category/category'
import comment from '../components/comment/comment'

const router = new VueRouter({
    routes:[
        {path:'/',redirect:'/admin/goodslist'},
        {name:"login",path:'/login',component:login,meta:{noNeedLogin:true}},
        {
            path:'/admin',component:layout,
            children:[
                {name:'goodslist',path:'goodslist',component:goodslist,meta:{menuId:'1-1'}},
                {path:'goodsadd',component:goodsadd,meta:{menuId:'1-1'}},
                {path:'goodsedit/:goodsId',component:goodsedit,meta:{menuId:'1-1'}},
                {path:'category',component:category,meta:{menuId:'1-2'}},
                {path:'comment',component:comment,meta:{menuId:'1-3'}}
            ]
        }
    ]
})

//设置全局路由守卫
router.beforeEach((to, from, next) => {
    if(to.meta.noNeedLogin){
        next()

        return
    }

    axios.get("admin/account/islogin").then(response=>{
        if(response.data.code=="nologin"){
            router.push({name:"login"})

            return
        }

        //将当前选中的菜单保存到localStorage中
        localStorage.setItem("currentMenuId",to.meta.menuId)

        next()
    })
})

export default router